package com.naizhuai.ui.user.userinfo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.ModelProvider;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.Model.db.user.UserDataSourse;
import com.naizhuai.Model.db.user.UserRepository;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.DialogSureCancel;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.UserUpdate;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStore;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AlbumUtils;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.UidUtil;
import com.naizhuai.util.ValidateUtil;
import com.naizhuai.util.ViewUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;

public class UserDetialActivity extends SwipeBackActivity {

    public static void start(Context context) {
        Intent intent = new Intent(context, UserDetialActivity.class);
        if (context instanceof BaseActivity)
            ((BaseActivity) context).startActivityTransition(intent);
    }

    @BindView(R.id.join_department)
    TextView joinDepartment;
    @BindView(R.id.operate_company)
    LinearLayout operateCompany;
    @BindView(R.id.userlogo)
    CircleImageView userlogo;
    @BindView(R.id.savedata)
    TextView savedata;
    @BindView(R.id.ed_name)
    EditText edName;
    @BindView(R.id.ed_department)
    EditText edDepartment;
    @BindView(R.id.ed_phonenumber)
    EditText edPhonenumber;
    @BindView(R.id.ed_email)
    EditText edEmail;
//    @BindView(R.id.exit_company)
//    TextView exitCompany;
    @BindView(R.id.exit_department)
    TextView exitDepartment;
    @BindView(R.id.toolbar)
    Toolbar Toolbar;
    @BindView(R.id.ed_department_Power)
    EditText edDepartmentPower;
    @BindView(R.id.ed_ComPany_Power)
    EditText edComPanyPower;
    private UserManageDataApiStore mUserManageDataApiStore;
    private UserRepository mUserRepository;
    private PersonUserBean mUserBean;
    private CompanyManageDataApiStore mCompanyManageapiStore;
    private int isSelf;
    private List<DepartmentBean> mDepartmentBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserManageDataApiStore = UserManageDataApiStoreIml.getInstance();
        mCompanyManageapiStore = CompanyManageDataApiStoreIml.getInstance();

        isSelf = ConstantsState.QUICK_BY_SELF;
        Toolbar.setNavigationOnClickListener(v -> finish());
        mUserRepository = ModelProvider.provideUserRepository();
        String uid = AccountHelper.getUid();
        mUserRepository.getUserAsyn(uid, new UserDataSourse.GetUserCallback() {
            @Override
            public void onUserLoaded(PersonUserBean user) {
                mUserBean = user;
                ViewUtils.showRoundImg(user.getUserLogoUrl(), userlogo);
                edName.setText(user.getShowName());
                edPhonenumber.setText(user.getPhoneNumber());
                edDepartmentPower.setText(user.getDepartmentPowerMsg());
                edComPanyPower.setText(user.getCompanyPowerMsg());
                edEmail.setText(user.getEmail());


                if ("".equals(user.getDepartmentId())){
                    edDepartment.setText(getString(R.string.not_department));
                }else {
                    edDepartment.setText(user.getDepartmentName());
                }


                if (TextUtils.isEmpty(mUserBean.getCompanyId())) {
                    operateCompany.setVisibility(View.GONE);
                } else {
                    operateCompany.setVisibility(View.VISIBLE);
                }
                if (TextUtils.isEmpty(mUserBean.getDepartmentId())) {
                    exitDepartment.setVisibility(View.GONE);
                    joinDepartment.setVisibility(View.VISIBLE);
                } else {
                    exitDepartment.setVisibility(View.VISIBLE);
                    joinDepartment.setVisibility(View.GONE);
                }
            }

            @Override
            public void onDataNotAvailable() {

            }
        });
        mCompanyManageapiStore.getTeamListInCompanyByIds(AccountHelper.getComPanyid())
                .subscribe(new NetWorkObserver<List<DepartmentBean>>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(List<DepartmentBean> result) {
                        mDepartmentBeans = result;
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_detial;
    }


    @OnClick(R.id.savedata)
    public void onSavedataClicked() {
        try {
            checkinput();
            updateUserData();
        } catch (ValidateException e) {
            shortToast(e.getMessage());
        }
    }

    private void updateUserData() {
        showWaitDialog(getString(R.string.data_update));
        mUserManageDataApiStore.userUpdate(ViewUtils.text(edName), "", ViewUtils.text(edEmail))
                .subscribe(new NetWorkObserver<UserUpdate>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(getString(R.string.action_fail));
                    }
                    @Override
                    protected void onSuccess(UserUpdate result) {
                        hideWaitDialog();
                        shortToast(getString(R.string.data_save_success));
                        finish();
                        RxBus.getDefault().postSticky(new Bus.UserChange());
                    }
                });
    }

    private void checkinput() throws ValidateException {
        if (TextUtils.isEmpty(ViewUtils.text(edName))) {
            throw new ValidateException(getString(R.string.please_real_name));
        }

        if (!TextUtils.isEmpty(ViewUtils.text(edEmail))&&!ValidateUtil.validateEamil(ViewUtils.text(edEmail)) ) {
            throw new ValidateException(getString(R.string.please_input_email_format));
        }
//        if (TextUtils.isEmpty(ViewUtils.text(edPhonenumber))) {
//            throw new ValidateException(getString(R.string.please_phonenumber));
//        }

    }

    //调用退出部门和退出公司的接口 然后调用加入部门的接口 然后要通知数据库的更新数据哈
//    @OnClick(R.id.exit_company)
//    public void onExitCompanyClicked() {
//        DialogSureCancel sureCancel = new DialogSureCancel(this);
//        sureCancel.setContent(getString(R.string.sure_exit_company));
//        sureCancel.getTvCancel().setOnClickListener(v -> sureCancel.cancel());
//        sureCancel.getTvSure().setOnClickListener(v -> {
//            sureCancel.cancel();
//            mCompanyManageapiStore.deletePersonFromCompanyByIds(null,
//                    null, new UidUtil(mUserBean.getUid()).toString(),
//                    ConstantsState.DELETE_FROM_COMPANY, isSelf)
//                    .subscribe(new NetWorkObserver<String>() {
//                        @Override
//                        protected void onFail(String errormsg) {
//                            shortToast(errormsg);
//                            hideWaitDialog();
//                        }
//
//                        @Override
//                        protected void onSuccess(String result) {
//                            hideWaitDialog();
//                            if (!ConstantsState.isResultOk(result)) {
//                                  shortToast(getResources().getString(R.string.action_fail));
//                            } else {
//                                // TODO: 2018/6/11退出公司成功之后的操作 后面的一系列操作 涉及到后面的权限判断问题
//                                shortToast(getResources().getString(R.string.action_ok));
//                                mUserRepository.updateLoginUser(new UserDataSourse.GetUserCallback() {
//                                    @Override
//                                    public void onUserLoaded(PersonUserBean user) {
//                                        edDepartmentPower.setText(user.getDepartmentPowerMsg());
//                                        edComPanyPower.setText(user.getCompanyPowerMsg());
//                                        AccountHelper.removeComPany();
//                                        RxBus.getDefault().postSticky(new Bus.UserChange());
//                                    }
//                                    @Override
//                                    public void onDataNotAvailable() {
//
//                                    }
//                                });
//                            }
//                        }
//                    });
//
//        });
//        sureCancel.show();
//    }

    @OnClick(R.id.exit_department)
    public void onExitDepartmentClicked() {
        DialogSureCancel sureCancel = new DialogSureCancel(this);
        sureCancel.setContent(getString(R.string.sure_exit_department));
        sureCancel.getTvCancel().setOnClickListener(v -> sureCancel.cancel());
        sureCancel.getTvSure().setOnClickListener(v -> {
            sureCancel.cancel();
            showWaitDiaLog();
            mCompanyManageapiStore.deletePersonFromCompanyByIds(mUserBean.getDepartmentId(),
                    null, new UidUtil(mUserBean.getUid()).toString(),
                    ConstantsState.DELETE_FROM_DEPARTMENT, isSelf)
                    .subscribe(new NetWorkObserver<String>() {
                        @Override
                        protected void onFail(String errormsg) {
                            shortToast(getString(R.string.action_fail));
                            hideWaitDialog();
                        }

                        @Override
                        protected void onSuccess(String result) {
                            hideWaitDialog();
                            if (!ConstantsState.isResultOk(result)) {
                                shortToast(getResources().getString(R.string.action_fail));
                            } else {
                                //退出部门成功之后 显示加入部门对文字和点击事件
                                exitDepartment.setVisibility(View.GONE);
                                joinDepartment.setVisibility(View.VISIBLE);

                                mUserRepository.updateLoginUser(new UserDataSourse.GetUserCallback() {
                                    @Override
                                    public void onUserLoaded(PersonUserBean user) {
                                        edDepartment.setText(user.getDepartmentName());
                                        edDepartmentPower.setText(user.getDepartmentPowerMsg());
                                        RxBus.getDefault().postSticky(new Bus.UserChange());
                                    }

                                    @Override
                                    public void onDataNotAvailable() {

                                    }
                                });

                            }
                        }
                    });
        });
        sureCancel.show();
    }

    @OnClick(R.id.join_department)
    public void joinDepartment() {
        initOptionsDepartment(mDepartmentBeans)
                .subscribe(bean -> {
                   showWaitDiaLog();
                    mCompanyManageapiStore.requestToJoinCompany(AccountHelper.getComPanyid(), bean.getDepartmentId(),
                            "申请加入部门")
                            .subscribe(new NetWorkObserver<String>() {
                                @Override
                                protected void onFail(String errormsg) {
                                    hideWaitDialog();
                                    shortToast(getString(R.string.action_fail));
                                }

                                @Override
                                protected void onSuccess(String result) {
                                    hideWaitDialog();
                                    if (!ConstantsState.isResultOk(result)) {
                                        shortToast(getResources().getString(R.string.action_fail));
                                    } else {
                                        //退出部门成功之后 显示加入部门对文字和点击事件
                                        exitDepartment.setVisibility(View.VISIBLE);
                                        joinDepartment.setVisibility(View.GONE);
                                        mUserRepository.updateLoginUser(new UserDataSourse.GetUserCallback() {
                                            @Override
                                            public void onUserLoaded(PersonUserBean user) {
                                                edDepartment.setText(user.getDepartmentName());
                                                edDepartmentPower.setText(user.getDepartmentPowerMsg());
                                            }

                                            @Override
                                            public void onDataNotAvailable() {

                                            }
                                        });
                                        RxBus.getDefault().postSticky(new Bus.UserChange());
                                    }
                                }
                            });
                });
    }


    private PublishSubject<DepartmentBean> initOptionsDepartment(List<DepartmentBean> result) {
        PublishSubject<DepartmentBean> subject = PublishSubject.create();
        OptionsPickerView<DepartmentBean> pvLabelOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> subject.onNext(result.get(options1)))
                .setTitleText(getString(R.string.label_selector))
                .setCancelColor(Color.GRAY)
                .setSubmitColor(getResources().getColor(R.color.lightorange))
                .setTextColorCenter(Color.LTGRAY)
                .build();
        pvLabelOptions.setPicker(result);
        pvLabelOptions.show();
        return subject;
    }

    @OnClick(R.id.userlogo)
    public void onUserlogoClicked() {
        AlbumUtils.singleChoice(this)
                .subscribe(albumFile -> updateUserAvator(albumFile.getPath()));

    }

    //
    private void updateUserAvator(String path) {
        showWaitDialog(getString(R.string.data_uploading));
        Observable.just(path)
                .map(imagepath -> {
                    //通过这个Path 压缩图片 并且返回压缩图片的路径 然后下发
                    Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
                    File file = BitmapUtils.changeBitmap2File(bitmap, UserDetialActivity.this, "temp.jpeg");
                    return file.getPath();
                })
                .flatMap(imagepath -> mUserManageDataApiStore.uploadImg(imagepath))
                .flatMap(bean -> mUserManageDataApiStore.userUpdate("", bean.getImgUrl(),
                        ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NetWorkObserver<UserUpdate>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(getString(R.string.action_fail));
                    }
                    
                    @Override
                    protected void onSuccess(UserUpdate result) {
                        hideWaitDialog();
                        ViewUtils.showRoundImg(result.thumb, userlogo);
                        mUserBean.setUserLogoUrl(result.thumb);
                        mUserRepository.updateLoginUser();
                        RxBus.getDefault().postSticky(new Bus.UserThumb(result.thumb));
                    }
                });
    }

}
